package cn.ssms.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 验证图片的URL是否有效
 * @author Administrator
 *
 */
public class CheckUtil {
	private static  CheckUtil checkUtil=new CheckUtil();
	/**
	 * 通过HttpURLConnection验证
	 * @throws MalformedURLException 
	 * @throws IOException 
	 * @throws ProtocolException 
	 */
	public boolean IsHttpUrlConnection(String url) throws IOException{
		HttpURLConnection conn = null;
		boolean flag;

			flag = checkUtil.urlCheck(url);
		
			if(flag){
			
				URL urlflag=new URL(url);
				conn =  (HttpURLConnection) urlflag.openConnection();
				conn.setDoInput(true);
				conn.setDoOutput(true);
				conn.setUseCaches(false);
				//请求GET
				conn.setRequestMethod("GET");
				
				conn.connect();

					if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
						String type = conn.getContentType();
						if(type.contains("image")){
							//System.out.println("图片");
							return true;
						}
						else {
								System.out.println("URL不为Image的");
								return false;
							}
					}else{
						System.out.println("URL不合法");
						return false;				
			}
			}
		return false;
	}
	/**
	 * 通过正则表达式，验证URL是否合法
	 * @param url
	 * @param imageName
	 * @return
	 * @throws IOException
	 */
	public boolean urlCheck(String urls) throws IOException{
		//通过正则表达式，验证URL是否合法
		String net = "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]" ;
       
		Matcher matcherNet = null;
		Pattern pattNet = Pattern. compile(net);
		matcherNet = pattNet.matcher(urls);
		return matcherNet.matches();
	}
	
	public static void main(String[] args) {
		//http://img4.imgtn.bdimg.com/it/u=2046345313,3976398763&fm=21&gp=0.jpg
		try {
			boolean falg=checkUtil.IsHttpUrlConnection("http://pic14.nipic.com/20110429/5786053_223227623000_2.jpg");
		   System.out.println(falg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	}
